#from os import listdir
from datetime import timedelta
from flask import Flask, request, render_template, url_for, Response, Request, jsonify, session,redirect # , send_file
from util import find_max_num, init_database, get_data, get_date, \
    create_dir, find_max_nums, export, find_time, \
    get_warn_data  # , export_excel, export_img ,get_time,save_path_dir,, check_temperature
#from zipfile import ZipFile
#from server import soc,Tcplink,send_command
#import simplejson#下载这个包可防止json不能解析decimal类型

app=Flask(__name__,static_folder='static',template_folder='templates')#配置模板文件的文件夹（html）
#app.config['JSON_AS_ASCII'] = False
#jiaja在云服务器用2.11.3不然报错


app.secret_key = 'tea-monitor'  # 设置session加密密钥
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 设置session过期时间为7天
app.config['SESSION_COOKIE_SECURE'] = True
scheme='http'#运行web.py用http否则用https

users = {'xy':'1234'}

@app.route('/index.html',methods=['POST','GET'])#main
def show_main():
    return render_template('./index.html')# ./

#相机推流
@app.route('/showimg.html',methods=['POST','GET'])#show_img
def show_img():
    return render_template('./showimg.html')# ./index.html

@app.route('/show_line',methods=['POST','GET'])#
def show_line():
    return render_template('./line_chart.html')# ./line_chart.html

@app.route('/water.html',methods=['POST','GET'])#
def show_water_line():
    return render_template('./water_chart.html')

@app.route('/bud.html',methods=['POST','GET'])#
def show_bud_line():
    return render_template('./bud_chart.html')

# @app.route('/check_temperature')
# def check_temperature():
#     db = init_database()
#     data = db.get_history_data(1)
#     temp = float(data[0][3])
#     if temp > 30:
#         print('too_hot')
#         return 'too_hot'
#     elif temp < 20:
#         return 'too_cold'
#     else:
#         return 'normal'

@app.route('/temperature.html',methods=['POST','GET'])#
def show_temperature_line():
    # sound = "../static/sound/test.py.wav"
    # if check_temperature():
    #     sound = "../static/sound/warn.wav"
    # db = init_database()
    # data = db.get_history_data(1)
    # temp = float(data[0][3])
    return render_template('./temperature_chart.html')#sound_url=sound,temperature=temp

@app.route('/humidity.html',methods=['POST','GET'])#
def show_humidity_line():
    return render_template('./humidity_chart.html')

@app.route('/history.html',methods=['POST','GET'])#
def show_history():
    return render_template('./history.html')

@app.route('/warn.html',methods=['POST','GET'])#
def show_warn():
    return render_template('./show_warn.html')

@app.route('/mine.html',methods=['POST','GET'])#
def show_mine():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))

    username = session['username']
    return render_template('./mine.html',username=username)

@app.route('/download.html',methods=['POST','GET'])#
def show_download():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return render_template('./download.html')

@app.route("/download")
def download():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export()

@app.route("/download1")
def download1():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(1)

@app.route("/download2")
def download2():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(2)

@app.route("/download3")
def download3():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(3)

@app.route("/download4")
def download4():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(4)

@app.route("/download5")
def download5():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(5)

@app.route("/download6")
def download6():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(6)

@app.route("/download7")
def download7():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(7)

@app.route("/download8")
def download8():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(8)

@app.route("/download9")
def download9():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(9)

@app.route("/download10")
def download10():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(10)

@app.route("/download11")
def download11():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(11)

@app.route("/download12")
def download12():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))
    return export(12)

# @app.route('/img_path',methods=['POST','GET'])#
# def get_img_path():
#     #if request.method=='GET':
#     i=find_max_num()
#     # while True:
#     #     if i!=0:
#     #         break
#     if i!=0:
#         save_dir = f'static/images/{get_date()}/'
#         img_path = save_dir + f'{i}.png'#get_time()#()
#     else:
#         img_path="static/images/tea2.png"
#     print('img_path:',img_path)
#     return img_path#'../'+

# @app.route('/img_paths',methods=['POST','GET'])#
# def get_img_paths():
#     #if request.method=='GET':
#     nums=find_max_nums()
#     save_dir = f'''static/images/{get_date()}/'''#.replace("'",'"')
#     img_paths=[save_dir + f"{num}.png" if num else "static/images/tea2.png" for num in nums]
#
#     # print('img_paths:',img_paths)
#     # #print('jsonify(img_paths):',jsonify(img_paths))
#     # return jsonify(img_paths)#转化为js需要的字符串，但无法将单引号转双引号
#     json_str =dumps(img_paths).replace("'",'"')
#     print('json_str:', json_str)
#     return json_str#由于返回的是一个 JSON 格式的字符串因此浏览器会自动按照 Content-Type 为 application/json 来解析返回内容
#
#     #如果浏览器不能解析则改用下面添加响应头
#     # response = make_response(json_str)
#     # response.headers["Content-Type"] = "application/json"
#     #
#     # return response

@app.route('/nums',methods=['POST','GET'])#
def get_img_paths():
    #if request.method=='GET':
    nums=find_max_nums()
    return jsonify(nums)#转化为js需要的字符串，但无法将单引号转双引号


# #相机喂流
# @app.route('/img_feed')
# def video_feed():
#     global count
#     print('开始')
#     #frame = ShootCamera(0).get_frame()
#     print('摄像头拍摄中')
#     img_path = save_img(ShootCamera(0))  # 'static/img/2023-3-30/(2).png'
#     count+=1
#     print('结束')
#     print('接收的图像路径：', img_path)
#     return img_path
#     #return Response(f'<img src={img_path} alt="拍摄图">')#原
#
# @app.route('/stop_shoot',methods=['POST','GET'])
# def stop_shoot():
#     i=find_max_num()
#     img_path = save_path_dir + f'({i}).png'
#     return render_template('./show_img.html',img=img_path)

@app.route('/line')
def get_line():
    db=init_database()
    data=db.get_history_data()
    print('接收data:',data)
    # print(len(data))
    # print(type(data))
    # print(data[1:])
    day, moisture_content, tender_bud_num, air_temperature, air_humidity=get_data(data)

    return jsonify({"day":day,"moisture_content":moisture_content,"tender_bud_num":tender_bud_num,"air_temperature":air_temperature,"air_humidity":air_humidity})

@app.route('/warn')
def get_warn():
    db = init_database()
    data = db.get_warn_data()
    print('已有warn:',data)
    day, msg = get_warn_data(data)

    return jsonify({"day": day, "msg": msg})

@app.route('/time')
def get_time():
    db=init_database()
    data=db.get_history_data(1)
    print('接收时间:',data[0][0])
    return str(data[0][0])

@app.route('/upload',methods=['POST','GET'])#
def upload():
    if request.method=='POST':
        file=request.files['file']
        print("收到文件：",file.filename)
        save_dir=f'static/images/{get_date()}/'
        create_dir(save_dir)
        file.save(f'./{save_dir}/{file.filename}')#{save_path_dir}/{file.filename}
        return "上传成功"
    else:
        return """
            <html><body>
            <h1>文件上传示例</h1>
            <form action="/upload" enctype='multipart/form-data' method='POST'>
                <input type='file' name='file'>
                <input type='submit' value='上传'>
            </form>
            </body></html>
        """

@app.route('/machine.html',methods=['POST','GET'])#
def control_machine():
    if 'username' not in session:  # 判断用户是否已登录
        return redirect(url_for('login',_external=True,_scheme=scheme))

    return render_template('./machine.html')#./show_img.html

@app.route('/accept_warn', methods=['POST'])
def accept_warn_msg():
    data = request.json
    msg=data['warn']
    t=find_time(msg)
    msg=msg.replace(t,'')
    db=init_database()
    data=db.get_warn_data()
    if data!=():
        days, msgs = get_warn_data(data)
        if (t not in days) and (msg not in msgs):
            db.insert_warn([t,msg])
    else:
        db.insert_warn([t, msg])
    # 处理数据...
    print('警告:',msg)
    return '已接收警告'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # print('username:',username)
        # print(f'{users[username]} == {password}')
        # print(f'{type(users[username])} == {type(password)}')
        # 判断用户名和密码是否正确
        if username in users and users[username] == password:
            session.permanent = True  # 设置session为永久
            session['username'] = username
            return redirect(url_for('show_main',_external=True,_scheme=scheme))

        return render_template('./login.html', error='用户名或密码错误！')

    return render_template('./login.html')

# 注销
@app.route('/logout')
def logout():
    session.pop('username', None)  # 从session中删除用户名
    session.permanent = False  # 设置session为临时状态
    return redirect(url_for('show_mine',_external=True,_scheme=scheme))


# past_data=''
# @app.route('/info',methods=['POST','GET'])#
# def get_info():
#     sock, addr = soc.accept()
#     data=Tcplink(sock, addr)
#     # if int(data)==2:
#     #if request.method=='POST':
#         # send_command(sock,'pause')
#     global past_data
#     if data!=b'':
#         print('data:', data)
#         past_data=data
#
#     return past_data

# @app.route('/start',methods=['POST','GET'])#
# def send_start_command():
#     sock, addr = soc.accept()
#     send_command(sock,'start')
#     return '已发送启动指令'
#
# @app.route('/pause',methods=['POST','GET'])#
# def send_pause_command():
#     sock, addr = soc.accept()
#     send_command(sock,'pause')
#     return '已发送暂停指令'
#
# @app.route('/5s',methods=['POST','GET'])#
# def send_5s_command():
#     sock, addr = soc.accept()
#     send_command(sock,'5s')
#     print("设置5s的检测指令")
#     return '已发送5s指令'
#
# @app.route('/10s',methods=['POST','GET'])#
# def send_10s_command():
#     sock, addr = soc.accept()
#     send_command(sock,'10s')
#     print("设置10s的检测指令")
#     return '已发送10s指令'
# @app.route('/30s',methods=['POST','GET'])#
# def send_30s_command():
#     sock, addr = soc.accept()
#     send_command(sock,'30s')
#     print("设置30s的检测指令")
#     return '已发送30s指令'
#
# @app.route('/1min',methods=['POST','GET'])#
# def send_1m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'1min')
#     print("设置1m的检测指令")
#     return '已发送1min指令'
#
# @app.route('/5min',methods=['POST','GET'])#
# def send_5m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'5min')
#     print("设置5min的检测指令")
#     return '已发送5min指令'
#
# @app.route('/10min',methods=['POST','GET'])#
# def send_10m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'10min')
#     print("设置10min的检测指令")
#     return '已发送10min指令'
#
# @app.route('/15min',methods=['POST','GET'])#
# def send_15m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'15min')
#     print("设置15min的检测指令")
#     return '已发送15min指令'
#
# @app.route('/30min',methods=['POST','GET'])#
# def send_30m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'30min')
#     print("设置30min的检测指令")
#     return '已发送30min指令'
#
# @app.route('/60min',methods=['POST','GET'])#
# def send_60m_command():
#     sock, addr = soc.accept()
#     send_command(sock,'60min')
#     print("设置60min的检测指令")
#     return '已发送60min指令'


# from flask_socketio import SocketIO,send,emit

# app.config['SECRET_KEY'] = 'secret!'
# socketio = SocketIO(app)


# @socketio.on('connect', namespace='/test.py')
# def test_connect():
#     emit('my response', {'data': 'Connected'})
#
#
# @socketio.on('disconnect', namespace='/test.py')
# def test_disconnect():
#     print('Client disconnected')
#
# @socketio.on('my event')
# def handle_my_custom_event(json):
#     emit('my response', json)

if __name__=='__main__':
    #CORS(app, supports_credentials=True)

    app.run(debug=True,host='0.0.0.0',port=8888,threaded=True)#False'127.0.0.1' localhost
    #http://127.0.0.1:8888/show_img
    #0.0.0.0 http://127.0.0.1:8888/video 192.168.199.213
    # SCAUNET http://172.20.31.75:8888/video  http://172.20.15.185:8888/video http://172.20.26.96:8888/show_img

    # socketio.run(app, host='0.0.0.0', debug=True,port=8888)